package net.towee.client.widgets;

import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.TextBox;

/**
 * Extended textbox needed for real-time processing inputing
 * string. It contain custom addChangeHandler method, that 
 * invoke handler after some waitDelay time or cancel and
 * renew timer if in this period of time user change entered string
 * 
 * @author c58
 */
public class SheduledInputBox extends TextBox {
	private Timer timer;
	private final int waitDelay = 250;
	
	public SheduledInputBox(){
		super();
	}
	
	public SheduledInputBox(final String helpString) {
		setText( helpString );
		setLayoutData(true);
		getElement().getStyle().setProperty("color", "#aaa");
		
		this.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(!helpString.isEmpty() && (Boolean)getLayoutData() == true) {
					getElement().getStyle().setProperty("color", "#000");
					setLayoutData(false);
					setText( "" );
				}
			}
		});
	}
	
	@Override
	public String getText() {
		if(getLayoutData() == null || (Boolean)getLayoutData() == false)
			return super.getText();
		else
			return "";
	}
	
	@Override
	public HandlerRegistration addChangeHandler(final ChangeHandler handler) {
		// ADd key up handler
		return addKeyUpHandler(new KeyUpHandler(){
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if(event.isAnyModifierKeyDown())
					return;
			
				if(timer != null)
					timer.cancel();

				timer = new Timer(){
					@Override
					public void run() {
						handler.onChange(null);
					}
				};

				timer.schedule(waitDelay);
			}
		});
	}
}
